package com.zhy.sping.util;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;

import java.util.Collection;
import java.util.Set;
import java.util.concurrent.TimeUnit;

public class RedissionUtil {
    private static RedissonClient client;
    static {
        Config config = new Config();
        config.useSingleServer().setAddress("redis://39.105.189.141:6380").setPassword("zzjava");
        client= Redisson.create(config);
    }

    //新增数据
    public static void addStr(String key,String val,int seconds){
        client.getBucket(key).set(val,seconds, TimeUnit.SECONDS);
    }

    public static void addSet(String key,Object val){
        client.getSet(key).add(val);
    }

    public static <T> void addSets(String key, Collection<T> vals){
        client.getSet(key).addAll(vals);
    }

    public static void addHash(String key,String feild,String val){
        client.getMap(key).put(feild,val);
    }
    //查询数据
    public static String getHash(String key,String feild){

        return client.getMap(key).get(feild).toString();
    }

    public static Object getStr(String key){
        return client.getBucket(key).get();
    }

    public static Set<Object> getSet(String keys){
        return client.getSet(keys).readAll();
    }

    public static Collection<Object> getZSet(String keys){
        return client.getSortedSet(keys).readAll();
    }

    //校验数据
    public static boolean checkHashFeild(String key,String feild){
        return client.getMap(key).containsKey(feild);
    }

    public static boolean checkKey(String key){
        return client.getKeys().countExists(key)>0;
    }

    public static boolean checkSet(String key,Object val){
        return client.getSet(key).contains(val);
    }
    //删除数据
    public static void delKey(String ... key){
        client.getKeys().delete(key);
    }

    public static String delHashFeild(String key,String feild){

        return client.getMap(key).remove(feild).toString();
    }
    //加锁  分布式锁
    public static RLock lock(String key){
        RLock rLock = client.getLock(key);
        return rLock;
    }

    public static RLock rlock(String key){
        return client.getLock(key);
    }

    //释放锁
    public static void unlock(String key){
        client.getLock(key).unlock();
    }
    //系统命令
    public static void expire(String key,long seconds){
        client.getKeys().expire(key,seconds,TimeUnit.SECONDS);
    }

    public static long ttl(String key){
        return client.getKeys().remainTimeToLive(key);
    }

    public static boolean exists(String ... keys){
        return client.getKeys().countExists(keys)>0;
    }

}
